package com.xjl.app.domain.tools;


import com.xjl.common.redis.tookit.CacheUtil;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class MQMessageThreadFactory implements ThreadFactory {

    private final AtomicInteger poolNumber = new AtomicInteger(1);

    private final AtomicInteger threadNumber = new AtomicInteger(1);

    private final ThreadGroup group;

    public final String namePrefix;

    MQMessageThreadFactory(String name){
        SecurityManager securityManager = System.getSecurityManager();
        group=(securityManager!=null)? securityManager.getThreadGroup(): Thread.currentThread().getThreadGroup();
        if(CacheUtil.isNullOrBlank(name)){
            name = "pool";
        }
        namePrefix = name+"-"+poolNumber.getAndIncrement()+"-thread-";
    }


    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if(thread.isDaemon()){
            thread.setDaemon(false);
        }
        if(thread.getPriority()!=Thread.NORM_PRIORITY){
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }
}
